package com.example;

import javax.swing.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Client implements Runnable, Message {
    public InputStream is;
    public OutputStream os;
    public ClientUI ui;


    public Client( ClientUI ui) {
        this.ui = ui;

        try {
            Socket socket = new Socket("127.0.0.1", 8888);
            os = socket.getOutputStream();
            is = socket.getInputStream();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run() {
        while(true){
            try {
                int head = is.read();
                switch (head){
                    case LOGIN:
                        handleLogin();
                        break;

                    case REGISTER:
                        break;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    public void handleLogin() throws Exception{
        int handle = is.read();
        if(handle == SUCCESS){
            ui.chatUI();
        }else  if(handle == ERROR){
            JOptionPane.showMessageDialog(null,"账号或密码错误，请重新输入！");
        }
    }


    public void sendMsg( String msg) throws Exception {

        String m = msg + "\r\n";
        os.write(m.getBytes());
        os.flush();
    }

    public String readMsg(InputStream is) throws Exception {

        byte[] b = new byte[1024];
        is.read(b);
        String s = new String(b);
        return s.trim();
    }

}
